package com.snda.lib.http;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import com.snda.lib.util.LibSettings;
import com.snda.lib.util.MD5Helper;
import com.snda.lib.util.MiscHelper;


import android.content.Context;

/**
 * 文件缓存，接收到的协议内容保存到文件中
 * 
 * @author Administrator
 * 
 */
public class FileCache {

	// 存储指定URL的响应数据
	public static boolean saveToCache(Context ctx, String strUrl,
			String strResponse) {

		String strSavePath = LibSettings.getResponsePath(ctx);
		File path = new File(strSavePath);
		if (path.exists() == false) {
			path.getParentFile().mkdirs();
		}
		path.mkdir();

		String strMD5Url = MD5Helper.getStringMD5(strUrl);
		strSavePath = strSavePath + strMD5Url + ".txt";
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(strSavePath,
					false));
			out.write(strResponse);
			out.close();
		} catch (IOException e) {
			return false;
		}

		return true;
	}

	public static String getFromCache(Context ctx, String strUrl) {

		String strSavePath = LibSettings.getResponsePath(ctx);
		String strMD5Url = MD5Helper.getStringMD5(strUrl);
		strSavePath = strSavePath + strMD5Url + ".txt";
		File file = new File(strSavePath);
		if (file.exists() == false) {
			return null;
		}

		try {
			FileInputStream fis = new FileInputStream(strSavePath);
			String strResponse = MiscHelper.inputStream2String(fis);
			fis.close();
			return strResponse;

		} catch (IOException e) {
			return null;
		}
	}
}
